#!/usr/bin/python
# -*- coding: utf-8 -*-

from twisted.web.client import getPage
import feedparser
import cairo
import pango
import os
import glib

from getlogo import *

DIR_IMG	= os.environ['HOME'] + '/.feedbar/images/'

def RSSdraw(self, window_to_draw, cr):
    self.window = window_to_draw


    # detecting pointer
    if self.pointer_on_bar == True:
#        print "checking"
        self.pointer = self.window.get_pointer()
        if  (0 <= self.pointer[0] <= (self.w/7)) and (0 <= self.pointer[1] <= self.h):
#            print "On Title"
            self.pointer_on_title = True
            self.pointer_on_rest = False
            #test
            self.tip = "Title"
        elif self.pointer[0] >= (self.w/7) and (0 <= self.pointer[1] <= self.h):
#            print "On Rest"
            self.pointer_on_rest = True
            self.pointer_on_title = False
            #test
            self.tip = "Rest"

        if self.pointer_on_title == True and self.movespeed == 0:
            try:
                self.movespeed = self.movespeedbef
                del self.movespeedbef
            except AttributeError:
                pass
        if self.pointer_on_rest == True and self.movespeed != 0:
            self.movespeedbef = self.movespeed
            self.movespeed = 0



    try:

    # determining best font size
        if not self.feeds[self.feedseq]['pango']:
            try:
                font_size = self.font_size
            except AttributeError:
                font_size = self.h
                cr.set_font_size(font_size)
                heights = {}
                for idx in range(self.feedrange[self.feedseq]):
                    (x, y, width, height, dx, dy) = cr.text_extents(self.feedcontent[self.feedseq].entries[idx].title)
                    heights[idx] = height
                idx_of_max_height = max((v,k) for (k,v) in heights.iteritems())[1]
                while height > (self.h * 0.64):
                    font_size -= 1
                    cr.set_font_size(font_size)
                    (x, y, width, height, dx, dy) = cr.text_extents(self.feedcontent[self.feedseq].entries[idx_of_max_height].title)
#                    print height, idx_of_max_height, font_size
                    
                self.font_size = font_size



        elif self.feeds[self.feedseq]['pango']:
            try:
                font_size = self.font_size

            except AttributeError:
                font_size = self.h
                layout = cr.create_layout()
                font = pango.FontDescription(self.font)
                font.set_size(int(font_size)*pango.SCALE)
                layout.set_font_description(font)
                heights = {}
                for idx in range(self.feedrange[self.feedseq]):
                    layout.set_text(self.feedcontent[self.feedseq].entries[idx].title)
                    width, heights[idx] = layout.get_pixel_size()
                idx_of_max_height = max((v,k) for (k,v) in heights.iteritems())[1]
                height = max((v,k) for (k,v) in heights.iteritems())[0]
                while height > (self.h * 0.64):
                    font_size -= 1
                    font.set_size(int(font_size)*pango.SCALE)
                    layout.set_font_description(font)
                    layout.set_text(self.feedcontent[self.feedseq].entries[idx].title)
                    width, height = layout.get_pixel_size()
#                    print height, idx_of_max_height, font_size
                    
                self.font_size = font_size


    
        
        for idx in range(self.feedrange[self.feedseq]):

            
            if not self.feeds[self.feedseq]['pango']:
                #temp
                cr.set_font_size(self.font_size + 1)
                if idx in self.width:
                    width = self.width[idx]
                elif idx not in self.width:
                    (x, y, width, height, dx, dy) = cr.text_extents(self.feedcontent[self.feedseq].entries[idx].title)
                    self.width[idx] = width
                    self.height_diff[idx] = -y - (height/2)
                    self.height_diff_min = min((value, key) for (key, value) in self.height_diff.items())[0]
#                    print x, y, width, height, dx, dy, self.height_diff[idx], self.height_diff_min

            elif self.feeds[self.feedseq]['pango']:
                if idx in self.layout:
                    layout = self.layout[idx]
                elif idx not in self.layout:
                    layout = cr.create_layout()
                    font = pango.FontDescription(self.font)
                    font.set_size(int(self.font_size + 1)*pango.SCALE)
                    layout.set_font_description(font)
                    layout.set_text(self.feedcontent[self.feedseq].entries[idx].title)
                    self.width[idx], self.height[idx] = layout.get_pixel_size()
                    self.layout[idx] = layout
#                    print self.height[idx]


            if not idx == 0:
                if not self.feeds[self.feedseq]['RtL']:
                    self.location[idx] = ((self.location[idx-1] + self.width[idx-1]) + 100 + self.inner_logo_width)
                elif self.feeds[self.feedseq]['RtL']:
                    self.location[idx] = ((self.location[idx-1] - self.width[idx]) - 100 - self.inner_logo_width)

#                print self.location[idx], self.location[idx - 1], self.width[idx - 1]

            elif idx == 0:
                if not self.feeds[self.feedseq]['RtL']:
                    self.location[idx] =  self.xLocation
                elif self.feeds[self.feedseq]['RtL']:
                    self.location[idx] =  self.xLocation - self.width[idx]


            self.startpoint = (self.window.allocation.width + 200)
            self.stoppoint = (-self.width[idx] -100)

            if self.location[idx] <= self.startpoint and self.location[idx] >= self.stoppoint:
                if not self.feeds[self.feedseq]['pango']:
                    cr.move_to(self.location[idx], self.h/2 + self.height_diff_min)
                    cr.show_text(self.feedcontent[self.feedseq].entries[idx].title)
                elif self.feeds[self.feedseq]['pango']:
                    cr.move_to(self.location[idx], self.h/2 - self.height[idx]/2)
                    cr.show_layout(self.layout[idx])



                cr.save()


                # drawing image (comsumes a bit more cpu)

                try:
                    inner_surface = self.inner_surface
                    inner_logo_height = self.inner_logo_height
                    inner_logo_width = self.inner_logo_width
                    inner_logo_opt_h = self.inner_logo_opt_h
                except AttributeError:
                    inner_surface = cairo.ImageSurface.create_from_png(DIR_IMG + self.logo_name)
                    inner_logo_height = float(inner_surface.get_height())
                    inner_logo_width = float(inner_surface.get_width())
                    new_height = self.h * 0.8
                    inner_logo_opt_h = (self.h/2 - (inner_logo_height)/2)
                    self.inner_surface = inner_surface
                    self.inner_logo_height = inner_logo_height
                    self.inner_logo_width = inner_logo_width
                    self.inner_logo_opt_h = inner_logo_opt_h
#                    print self.h, inner_logo_opt_h

                if not idx == (self.feedrange[self.feedseq] - 1):

                    if not self.feeds[self.feedseq]['RtL']:
                        self.inner_logo_location[idx] = self.location[idx] + self.width[idx] + 50
                    elif self.feeds[self.feedseq]['RtL']:
                        self.inner_logo_location[idx] = self.location[idx] - (inner_logo_width) - 50


                    if self.inner_logo_location[idx] <= self.startpoint and self.inner_logo_location[idx] >= self.stoppoint:

                        cr.rectangle (self.inner_logo_location[idx], inner_logo_opt_h, inner_logo_width, inner_logo_height)
                        cr.set_source_surface(inner_surface, self.inner_logo_location[idx], inner_logo_opt_h)
                        cr.fill()

                cr.restore()

    except KeyError as keyErr:
#        print "Loading, current sequence", self.feedseq, keyErr
        if not self.feeds[self.feedseq]['RtL']:
            self.xLocation = self.w + 100
        elif self.feeds[self.feedseq]['RtL']:
            self.xLocation = 0



def RSSdownload(self, feedlink, seq):
    # Downloading the feed page using twisted
    for n in range(3):
#        try:
        self.downloadedfeed = getPage(feedlink)
        self.downloadedfeed.addCallback(RSSmanage, self, seq)
        #test
        self.downloadedfeed.addErrback(errorHandler, self, seq)
        print "Starting downloading for feed {0}:{1}".format(seq, self.feeds[seq]['feed_title'])
        break
#        except:
#            print "Problem downloading feed {0}:{1}".format(seq, self.feeds[seq][1])


def RSSmanage(output, self, seq):
    self.out[seq] = output
#    print output
    print "Done downloading for feed {0}:{1}".format(seq, self.feeds[seq]['feed_title'])
#1st problem
    if seq == 0 and self.feedseq == 0 and not self.collapsed:
        parse(self, output, seq)
    self.task_done = True



def parse(self, string, seq):
    # Parsing the downloaded feed
    print "Parsing feed {0}:{1}".format(seq, self.feeds[seq]['feed_title'])
    self.feedcontent[seq] = feedparser.parse(string)

    # determining the number of entries to show
    if self.feeds[self.feedseq]['feedmax'] >= len(self.feedcontent[seq]['entries']):
        self.feedrange[seq] = len(self.feedcontent[seq]['entries'])
    elif self.feeds[self.feedseq]['feedmax'] < len(self.feedcontent[seq]['entries']):
        self.feedrange[seq] = self.feeds[self.feedseq]['feedmax']


    # the logo link
    self.logo_name = False
    try:
        if self.feedcontent[seq].feed.links[0].type == 'application/atom+xml':
            self.logo[seq] = self.feedcontent[seq].feed.logo
        else:
            self.logo[seq] = self.feedcontent[seq].feed.image.href
    # dont forget the error
    except AttributeError:
        self.logo[seq] = 'http://taljurf.fedorapeople.org/Scratch/FeedLine/icon.png'

    logo_name_old = os.path.basename(self.logo[seq])
    basename, extension = os.path.splitext(logo_name_old)
    self.logo_name = basename + '.png'
#    print self.logo_name

    getlogo(str(self.logo[seq]), self.h)


#    print self.logo[seq]

    print "Parsed feed {0}:{1}".format(seq, self.feeds[seq]['feed_title'])
#TESSTT vvvvvvvvv
#    len(self.feedcontent[seq]['entries'])
#    print len(self.feedcontent[seq]['entries'])


def errorHandler(failure, self, seq):
    """Error Handling"""
    print "Connection Problem, retrying in 20 seconds"
    glib.timeout_add_seconds(20, get_again, self, seq)

def get_again(self, seq):
    feed_type = self.feeds[seq]['feed_type']
    self.optionsavail[feed_type][1](self, self.feeds[seq]['feed_link'], seq)
